package com.kxmall.web.controller.huishou;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kxmall.common.annotation.Log;
import com.kxmall.common.annotation.RepeatSubmit;
import com.kxmall.common.core.controller.BaseController;
import com.kxmall.common.core.domain.BaseEntity;
import com.kxmall.common.core.domain.PageQuery;
import com.kxmall.common.core.domain.R;
import com.kxmall.common.core.page.TableDataInfo;
import com.kxmall.common.core.validate.AddGroup;
import com.kxmall.common.core.validate.EditGroup;
import com.kxmall.common.enums.BusinessType;
import com.kxmall.common.excel.ExcelResult;
import com.kxmall.common.utils.DateUtils;
import com.kxmall.common.utils.poi.ExcelUtil;
import com.kxmall.huishou.domain.HsSettlementOrder;
import com.kxmall.huishou.domain.bo.HsSettlementOrderBo;
import com.kxmall.huishou.domain.bo.HsTimeBo;
import com.kxmall.huishou.domain.bo.HsUserWasteBo;
import com.kxmall.huishou.domain.vo.HsSettlementOrderExport;
import com.kxmall.huishou.domain.vo.HsSettlementOrderVo;
import com.kxmall.huishou.domain.vo.HsUserWasteVo;
import com.kxmall.huishou.mapper.HsSettlementOrderMapper;
import com.kxmall.huishou.service.IHsSettlementOrderService;
import com.kxmall.huishou.service.IHsUserWasteService;
import com.kxmall.rider.domain.vo.KxRiderVo;
import com.kxmall.user.domain.KxUser;
import com.kxmall.web.controller.huishou.listeners.SettlementOrderImportListener;
import com.kxmall.web.controller.rider.service.IKxRiderService;
import com.kxmall.web.controller.user.service.IKxUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 回收结算订单信息
 *
 * @author kxmall
 * @date 2023-11-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/huishou/settlementOrder")
@Slf4j
public class HsSettlementOrderController extends BaseController {

    private final IHsSettlementOrderService iHsSettlementOrderService;

    private final IHsUserWasteService iHsUserWasteService; // 废品信息

    private final IKxRiderService iKxRiderService; // 配送员
    /**
     * 下单用户
     */
    private final IKxUserService iKxUserService;

    private final HsSettlementOrderMapper baseMapper;

    /**
     * 查询回收结算订单信息列表
     */
    @SaCheckPermission("huishou:settlementOrder:list")
    @GetMapping("/list")
    public TableDataInfo<HsSettlementOrderVo> list(HsSettlementOrderBo bo, PageQuery pageQuery) {
        TableDataInfo<HsSettlementOrderVo> queryPageList = iHsSettlementOrderService.queryPageList(bo, pageQuery);
        for (HsSettlementOrderVo row : queryPageList.getRows()) {
            try{
                KxRiderVo kxRiderVo = iKxRiderService.queryById(row.getRiderId());
                row.setRiderPhone(kxRiderVo.getPhone());
                row.setRiderName(kxRiderVo.getName());
            }
            catch (Exception e) {log.info(row.getRiderId() + "：回收员不存在");}
        }
        return queryPageList;
    }

    /**
     * 导出回收结算订单信息列表
     */
    @SaCheckPermission("huishou:settlementOrder:export")
    @Log(title = "回收结算订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HsTimeBo bo, HttpServletResponse response) {
        List<HsSettlementOrderExport> exportList = new ArrayList<>();
        HashMap<Long, String> mapType = new HashMap<>();
        mapType.put(0L,"结算中,未确认");
        mapType.put(1L,"已确认通过，未支付");
        mapType.put(2L,"确认不通过");
        mapType.put(3L,"已支付，待确认");
        mapType.put(4L,"支付成功，完结");
        mapType.put(5L,"支付失败");
        mapType.put(6L,"失败，完结");
        LambdaQueryWrapper<HsSettlementOrder> q = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(bo.getStartTime()) && StringUtils.isNotEmpty(bo.getEndTime()) ){
            DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
            DateTime startTime = dateTimeFormatter.parseDateTime(bo.getStartTime());
            DateTime endTime = dateTimeFormatter.parseDateTime(bo.getEndTime());
            Date newDate = DateUtils.addDays(endTime.toDate(), 1);
            q.ge(HsSettlementOrder::getCreateTime,startTime.toDate());
            q.lt(HsSettlementOrder::getCreateTime,newDate);
        }
        q.orderByDesc(BaseEntity::getCreateTime);
        List<HsSettlementOrderVo> settlementOrderVoList = baseMapper.selectVoList(q);
        List<Long> userIdList = settlementOrderVoList.stream().map(HsSettlementOrderVo::getUserId).distinct().collect(Collectors.toList());
        Map<Long,KxUser> userHashMap = new HashMap<>();
        if (CollUtil.isNotEmpty(userIdList)) {
            List<KxUser> kxUsers = iKxUserService.listByIds(userIdList);
            if (CollUtil.isNotEmpty(kxUsers)) {
                userHashMap = kxUsers.stream().collect(Collectors.toMap(KxUser::getUid, item->item));
            }
        }


        // 获取所有订单id 及 回收员id
        for (HsSettlementOrderVo row : settlementOrderVoList) {
            KxRiderVo kxRiderVo = new KxRiderVo();
            try{kxRiderVo = iKxRiderService.queryById(row.getRiderId());}
            catch (Exception e) {log.info(row.getRiderId() + "：回收员不存在");}

            HsUserWasteBo wasteBo = new HsUserWasteBo();
            wasteBo.setOrderId(row.getId());
            wasteBo.setOrderType(1L);
            List<HsUserWasteVo> wasteVoList = iHsUserWasteService.queryList(wasteBo);

            for (HsUserWasteVo hsUserWasteVo : wasteVoList) {
                HsSettlementOrderExport orderExport = new HsSettlementOrderExport();
                // 订单编号 支付状态 时间
//                orderExport.setOrderNo(row.getOrderNo());
                orderExport.setStatusName(mapType.get(row.getStatus()));
                orderExport.setCreateTime(row.getCreateTime());
                // 名称 手机号
//                orderExport.setRiderName(kxRiderVo.getName());
                orderExport.setRiderPhone(kxRiderVo.getPhone());
                KxUser kxUser = userHashMap.get(row.getUserId());
                if (kxUser != null) {
                    orderExport.setUserPhone(kxUser.getPhone());
                }
                // 分类 价格 金额 重量
                orderExport.setCategorizeName(hsUserWasteVo.getCategorizeName());
                orderExport.setPrice(hsUserWasteVo.getPrice());
                orderExport.setAmount(hsUserWasteVo.getAmount());
                orderExport.setWeight(hsUserWasteVo.getWeight());
                exportList.add(orderExport);
            }
        }
        ExcelUtil.exportExcel(exportList, "回收结算订单信息", HsSettlementOrderExport.class, response);
    }

    /**
     * 导出回收结算订单信息列表
     */
    @SaCheckPermission("huishou:settlementOrder:import")
    @Log(title = "导入回收结算订单信息", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public R<Void> importData(@RequestPart("file") MultipartFile file) throws IOException {
        ExcelResult<HsSettlementOrderExport> result = ExcelUtil.importExcel(file.getInputStream(), HsSettlementOrderExport.class, new SettlementOrderImportListener());
        return R.ok(result.getAnalysis());
    }

    /**
     * 导出回收结算订单信息模板
     */
    @SaCheckPermission("huishou:settlementOrder:template")
    @PostMapping("/template")
    public void exportTemplateData( HttpServletResponse response) {
        List<HsSettlementOrderExport> exportList = new ArrayList<>();
        ExcelUtil.exportExcel(exportList, "回收结算订单信息", HsSettlementOrderExport.class, response);
    }

    /**
     * 获取回收结算订单信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("huishou:settlementOrder:query")
    @GetMapping("/{id}")
    public R<HsSettlementOrderVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        HsSettlementOrderVo hsSettlementOrderVo = iHsSettlementOrderService.queryById(id);
        if(hsSettlementOrderVo != null){
            try{
                KxRiderVo kxRiderVo = iKxRiderService.queryById(hsSettlementOrderVo.getRiderId());
                hsSettlementOrderVo.setRiderPhone(kxRiderVo.getPhone());
            }
            catch (Exception e) {log.info(hsSettlementOrderVo.getRiderId() + "：回收员不存在");}
            HsUserWasteBo hsUserWasteBo = new HsUserWasteBo();
            hsUserWasteBo.setOrderId(id);
            hsUserWasteBo.setOrderType(1l);
            List<HsUserWasteVo> hsUserWasteVoList = iHsUserWasteService.queryList(hsUserWasteBo);
            hsSettlementOrderVo.setHsUserWasteVoList(hsUserWasteVoList);
        }

        return R.ok(hsSettlementOrderVo);
    }

    /**
     * 新增回收结算订单信息
     */
    @SaCheckPermission("huishou:settlementOrder:add")
    @Log(title = "回收结算订单信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody HsSettlementOrderBo bo) {
        return toAjax(iHsSettlementOrderService.insertByBo(bo));
    }

    /**
     * 修改回收结算订单信息
     */
    @SaCheckPermission("huishou:settlementOrder:edit")
    @Log(title = "回收结算订单信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody HsSettlementOrderBo bo) {
        return toAjax(iHsSettlementOrderService.updateByBo(bo));
    }

    /**
     * 删除回收结算订单信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("huishou:settlementOrder:remove")
    @Log(title = "回收结算订单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iHsSettlementOrderService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
